package cn.christ.com.mobilesafe.engine;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.christ.com.mobilesafe.modle.AppInfo;

public class AppProvider {

	public static List<AppInfo> getAppInfos(Context context) {
		List<AppInfo> appInfos = new ArrayList<AppInfo>();
		// 1 获取PackageManager对象
		PackageManager pm = context.getPackageManager();
		// 2 通过PackageManager的getInstalledPackages的方法获取List<PackageInfo>
		List<PackageInfo> infos = pm.getInstalledPackages(0);
		// 3 迭代PackageInfo的列表
		for (PackageInfo info : infos) {
			
			AppInfo appInfo = new AppInfo();
			appInfo.packageName=info.packageName;
			// 4 通过PackageInfo获取ApplicatoinInfo的对象
			ApplicationInfo applicationInfo = info.applicationInfo;
			// 5 通过ApplicatoinInfo的对象的loadIcon方法，获取图标
			appInfo.icon = applicationInfo.loadIcon(pm);
			// 6 通过ApplicatoinInfo的对象的loadLabel方法，获取应用名字
			appInfo.name = applicationInfo.loadLabel(pm).toString();
			// 7 通过ApplicatoinInfo的对象的sourceDir,获取路径，从而获取apk的大小
			File file = new File(applicationInfo.sourceDir);
			appInfo.apkSize = file.length();
			// 8 是否安装sd卡，是否是系统应用？？？
			//是否安装sd卡
			int flags = applicationInfo.flags;
			if ((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE) {
				appInfo.isInstallSD = true;
			} else {
				appInfo.isInstallSD = false;
			}
			
			if((flags&ApplicationInfo.FLAG_SYSTEM)==ApplicationInfo.FLAG_SYSTEM){
				appInfo.isSystem=true;
			}else{
				appInfo.isSystem=false;
			}
			appInfos.add(appInfo);
		}
		return appInfos;
	}

	public static AppInfo getAllAppInfo(Context context, String packageName) {
		PackageManager pm = context.getPackageManager();
		PackageInfo info;
		AppInfo appInfo = null;
		try {
			info = pm.getPackageInfo(packageName, 0);
			appInfo = new AppInfo();
			appInfo.packageName = info.packageName;
			// 4 通过PackageInfo获取ApplicatoinInfo的对象
			ApplicationInfo applicationInfo = info.applicationInfo;
			// 5 通过ApplicatoinInfo的对象的loadIcon方法，获取图标
			appInfo.icon = applicationInfo.loadIcon(pm);
			// 6 通过ApplicatoinInfo的对象的loadLabel方法，获取应用名字
			appInfo.name = applicationInfo.loadLabel(pm).toString();
			// 7 通过ApplicatoinInfo的对象的sourceDir,获取路径，从而获取apk的大小
			File file = new File(applicationInfo.sourceDir);
			appInfo.apkSize = file.length();
			// 8 是否安装sd卡，是否是系统应用？？？
			// 是否安装sd卡
			int flags = applicationInfo.flags;
			if ((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE) {
				appInfo.isInstallSD = true;
			} else {
				appInfo.isInstallSD = false;
			}

			if ((flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
				appInfo.isSystem = true;
			} else {
				appInfo.isSystem = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return appInfo;
	}
}
